package module.modbus.rtu;
import util.SerialTool;

import java.util.Random;

/**
 * @author bingo
 * @Description
 * @Date 2018/8/13
 */
public class RtuStartThread implements  Runnable {

    private ModbusRtu serialPortRtu;

    public static  boolean isLocked = true;


    public RtuStartThread() {

        serialPortRtu = new ModbusRtu();
    }


    @Override
    public void run() {
        int[] slaveId = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] methodCode = new int[]{3, 6, 16};
        Random random = new Random();
        int count=0;
        serialPortRtu.open(SerialTool.getCommPortIdentifier("COM1"));
        while (true) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int slave = random.nextInt(slaveId.length);
            int code = random.nextInt(methodCode.length);
            short[] data = null;
            if (methodCode[code] == 6) {
                data = new short[1];
                data[0] = (short) random.nextInt(Short.MAX_VALUE);
            } else if (methodCode[code] == 3) {
                data = new short[1];
                data[0] = (short) random.nextInt(10);
            } else if (methodCode[code] == 16) {
                data = new short[10];
                for (int i = 0; i < 10; i++) {
                    data[i] = (short) random.nextInt(Short.MAX_VALUE);
                }
            }
            count++;
            System.out.println("正在发送第【"+count+"】条数据");
            serialPortRtu.send(slaveId[slave], methodCode[code], 0, data);



        }
    }

    public ModbusRtu getSerialPortRtu(){
        return serialPortRtu;
    }


}
